package com.itheima.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.dao.SpecMapper;
import com.itheima.goods.pojo.Spec;
import com.itheima.goods.service.SpecService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SpecServiceimpl implements SpecService {

    @Autowired
    private SpecMapper specMapper;

    @Override
    public Result findAll() {
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        List<Spec> specList = specMapper.selectList(wrapper);

        return new Result(true, StatusCode.OK,"",specList);
    }

    @Override
    public Result add(Spec spec) {
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        wrapper.eq("id",spec.getId());
        Spec selectOne = specMapper.selectOne(wrapper);
        if(selectOne!=null){
            return new Result(false,StatusCode.ERROR,"数据库已存在",null);
        }
        int insert = specMapper.insert(spec);
        return new Result(true,StatusCode.OK,"",insert);
    }

    @Override
    public Result findPage(Integer size, Integer page) {
        IPage<Spec> iPage=new Page<>(1,4);
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        IPage<Spec> iPage1 = specMapper.selectPage(iPage, wrapper);
        List<Spec> records = iPage1.getRecords();
        PageResult<Spec> objectPageResult = new PageResult<>();
        objectPageResult.setRows(records);
        objectPageResult.setTotal(iPage1.getTotal());
        return new Result(true,StatusCode.OK,"",objectPageResult);
    }

    @Override
    public Result delete(Integer id) {
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        int delete = specMapper.delete(wrapper);
        return new Result(true,StatusCode.OK,"",delete);
    }

    @Override
    public Result update(Integer id, Spec spec) {
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        int update = specMapper.update(spec, wrapper);
        return new Result(true,StatusCode.OK,"",update);
    }

    @Override
    public Result findById(Integer id) {
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        Spec spec = specMapper.selectOne(wrapper);
        return new Result(true,StatusCode.OK,"",spec);
    }
}
